package cn.zhangjie.basic.controller;

import cn.zhangjie.basic.util.FastDfsUtils;
import cn.zhangjie.basic.util.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {
    @PostMapping
    public JsonResult upload(@RequestPart(value ="file",required = true) MultipartFile file){

        try {
            //获取原始文件
            String originalFilename = file.getOriginalFilename();
            //获取文件的后缀
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //调用工具类中的upload方法
            String path = FastDfsUtils.upload(file.getBytes(),substring);
            //把path设置给jsonresult中的resultobj
            return JsonResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("上传失败");
        }
    }

    @DeleteMapping
    public JsonResult delete(@RequestParam(value ="path",required = true) String path){
        try {
            String pathTmp = path.substring(1);
            String gourpname = pathTmp.substring(0, pathTmp.indexOf("/"));
            String remotepath = pathTmp.substring(pathTmp.indexOf("/") + 1);
            FastDfsUtils.delete(gourpname,remotepath);
            return JsonResult.me();

        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }


    }















}
